using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using FarPoint.Win.Spread;
using FarPoint.Win.Spread.Model;

namespace Spread.FloatingObjects.Features
{
    public partial class ChildControls : Spread.Common.Features.Sample.BaseSampleControl
    {
        private Dictionary<string, int> _instanceCounters;

        public ChildControls()
        {
            InitializeComponent();
            Name = "Child Controls";

            _instanceCounters = new Dictionary<string, int>()
            {
                { "SpreadButton", 0 },
                { "SpreadTextBox", 0 },
                { "SpreadCheckBox", 0 },
                { "SpreadRadioButton", 0 },
                { "SpreadComboBox", 0 }
            };

            comboControls.SelectedIndex = -1;

            comboControls.Items.AddRange(new object[] { "Button", "TextBox", "CheckBox", "RadioButton", "ComboBox" });

            InitSpreadSheet(fpSpread.ActiveSheet);

            comboControls.SelectedIndexChanged += ComboControls_SelectedIndexChanged;
            btnAddControl.Click += BtnAddControl_Click;
            fpSpread.EnterCell += FpSpread_EnterCell;
        }

        private void InitSpreadSheet(SheetView sheet)
        {
            fpSpread.ActiveSheet.SetMultipleRowHeights(0, fpSpread.ActiveSheet.RowCount, 25);
            fpSpread.ActiveSheet.SetMultipleColumnWidths(0, fpSpread.ActiveSheet.ColumnCount, 90);

            AddSpreadControl(sheet, typeof(SpreadButton), 1, 1);
            AddSpreadControl(sheet, typeof(SpreadTextBox), 1, 3);
            AddSpreadControl(sheet, typeof(SpreadCheckBox), 1, 5);
            AddSpreadControl(sheet, typeof(SpreadRadioButton), 3, 2);
            AddSpreadControl(sheet, typeof(SpreadComboBox), 3, 4);
        }

        #region Event handlers
        private void FpSpread_EnterCell(object sender, EnterCellEventArgs e)
        {
            Rectangle rectangle = fpSpread.GetCellRectangle(0, 0, e.Row, e.Column);
            Control control = fpSpread.GetChildAtPoint(rectangle.Location);
            propertyGrid.SelectedObject = control;
        }

        private void ComboControls_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnAddControl.Enabled = (comboControls.SelectedItem != null);
        }

        private void BtnAddControl_Click(object sender, EventArgs e)
        {
            SheetView sheet = fpSpread.ActiveSheet;

            string controlName = comboControls.SelectedItem.ToString();

            Type type = null;
            switch (controlName)
            {
                case "Button":
                    type = typeof(SpreadButton);
                    break;
                case "TextBox":
                    type = typeof(SpreadTextBox);
                    break;
                case "CheckBox":
                    type = typeof(SpreadCheckBox);
                    break;
                case "RadioButton":
                    type = typeof(SpreadRadioButton);
                    break;
                case "ComboBox":
                    type = typeof(SpreadComboBox);
                    break;
            }

            CellRange range = fpSpread.ActiveSheet.GetSelection(0);
            Control control = null;
            if (range.IsValidRange(fpSpread.ActiveSheet))
            {
                for (int row = range.Row; row < range.Row + range.RowCount; ++row)
                {
                    for (int col = range.Column; col < range.Column + range.ColumnCount; ++col)
                    {
                        control = AddSpreadControl(sheet, type, row, col);
                    }
                }
            }
            propertyGrid.SelectedObject = control;
        }

        private Control AddSpreadControl(SheetView sheet, Type type, int row, int col)
        {
            Control control = Activator.CreateInstance(type.Assembly.FullName, type.FullName).
                            Unwrap() as Control;
            control.Name = $"{type.Name}{++_instanceCounters[type.Name]}";
            control.Text = control.Name;
            control.Size = new Size((int)sheet.Columns[col].Width, (int)sheet.Rows[row].Height);
            control.GotFocus += Control_GotFocus;
            control.Left = 50;
            control.Top = 75;

            fpSpread.AddControl(control, fpSpread.ActiveSheetIndex, row, col);
            listBox.Items.Add($"Added: {control.Name}");

            return control;
        }

        private void Control_GotFocus(object sender, EventArgs e)
        {
            propertyGrid.SelectedObject = sender;
        }
        #endregion
    }
}

//
//ChildControls.designer.cs
//

namespace Spread.FloatingObjects.Features
{
    partial class ChildControls
    {
        /// <summary> 
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.comboControls = new System.Windows.Forms.ComboBox();
            this.label1 = new System.Windows.Forms.Label();
            this.listBox = new System.Windows.Forms.ListBox();
            this.propertyGrid = new System.Windows.Forms.PropertyGrid();
            this.fpSpread = new FarPoint.Win.Spread.FpSpread();
            this.fpSpread_Sheet1 = new FarPoint.Win.Spread.SheetView();
            this.btnAddControl = new System.Windows.Forms.Button();
            this.pnlMain.SuspendLayout();
            this.pnlControls.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.fpSpread)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.fpSpread_Sheet1)).BeginInit();
            this.SuspendLayout();
            // 
            // pnlMain
            // 
            this.pnlMain.Controls.Add(this.fpSpread);
            // 
            // pnlControls
            // 
            this.pnlControls.Controls.Add(this.btnAddControl);
            this.pnlControls.Controls.Add(this.propertyGrid);
            this.pnlControls.Controls.Add(this.listBox);
            this.pnlControls.Controls.Add(this.label1);
            this.pnlControls.Controls.Add(this.comboControls);
            // 
            // comboControls
            // 
            this.comboControls.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.comboControls.FormattingEnabled = true;
            this.comboControls.Location = new System.Drawing.Point(10, 35);
            this.comboControls.Name = "comboControls";
            this.comboControls.Size = new System.Drawing.Size(133, 21);
            this.comboControls.TabIndex = 0;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(10, 16);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(76, 13);
            this.label1.TabIndex = 1;
            this.label1.Text = "Select Control:";
            // 
            // listBox
            // 
            this.listBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.listBox.FormattingEnabled = true;
            this.listBox.Location = new System.Drawing.Point(10, 100);
            this.listBox.Name = "listBox";
            this.listBox.Size = new System.Drawing.Size(133, 134);
            this.listBox.TabIndex = 2;
            // 
            // propertyGrid
            // 
            this.propertyGrid.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
            | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.propertyGrid.Location = new System.Drawing.Point(10, 252);
            this.propertyGrid.Name = "propertyGrid";
            this.propertyGrid.Size = new System.Drawing.Size(133, 221);
            this.propertyGrid.TabIndex = 3;
            // 
            // fpSpread
            // 
            this.fpSpread.Dock = System.Windows.Forms.DockStyle.Fill;
            this.fpSpread.Location = new System.Drawing.Point(0, 0);
            this.fpSpread.Name = "fpSpread";
            this.fpSpread.Sheets.AddRange(new FarPoint.Win.Spread.SheetView[] {
            this.fpSpread_Sheet1});
            this.fpSpread.Size = new System.Drawing.Size(477, 487);
            this.fpSpread.Skin = FarPoint.Win.Spread.DefaultSpreadSkins.Office2016White;
            this.fpSpread.StatusBarVisible = true;
            this.fpSpread.TabIndex = 0;
            // 
            // fpSpread_Sheet1
            // 
            this.fpSpread_Sheet1.Reset();
            this.fpSpread_Sheet1.SheetName = "Sheet1";
            // Formulas and custom names must be loaded with R1C1 reference style
            this.fpSpread_Sheet1.ReferenceStyle = FarPoint.Win.Spread.Model.ReferenceStyle.R1C1;
            this.fpSpread_Sheet1.ReferenceStyle = FarPoint.Win.Spread.Model.ReferenceStyle.A1;
            // 
            // btnAddControl
            // 
            this.btnAddControl.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.btnAddControl.Enabled = false;
            this.btnAddControl.Location = new System.Drawing.Point(36, 64);
            this.btnAddControl.Name = "btnAddControl";
            this.btnAddControl.Size = new System.Drawing.Size(75, 23);
            this.btnAddControl.TabIndex = 4;
            this.btnAddControl.Text = "Add Control";
            this.btnAddControl.UseVisualStyleBackColor = true;
            // 
            // ChildControls
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Name = "ChildControls";
            this.pnlMain.ResumeLayout(false);
            this.pnlControls.ResumeLayout(false);
            this.pnlControls.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.fpSpread)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.fpSpread_Sheet1)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.ComboBox comboControls;
        private FarPoint.Win.Spread.FpSpread fpSpread;
        private FarPoint.Win.Spread.SheetView fpSpread_Sheet1;
        private System.Windows.Forms.PropertyGrid propertyGrid;
        private System.Windows.Forms.ListBox listBox;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Button btnAddControl;
    }
}


//
//CustomChildControls.cs
//


using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using FarPoint.Win.Spread.DrawingSpace;

namespace Spread.FloatingObjects
{
    public class SpreadButton : Button, IEmbeddedControlSupport
    {
        public virtual Moving CanMove { get; set; } = Moving.None;
        public virtual Sizing CanSize { get; set; } = Sizing.None;
        public virtual ChildActivationPolicy ActivationPolicy { get; set; } = ChildActivationPolicy.Click;

        public void ControlPaint(Graphics g, Rectangle r, FarPoint.Win.Spread.Appearance appearance, object value, bool isSelected, bool isLocked, float zoomFactor)
        {
            Region rgn = g.Clip;
            g.SetClip(r, CombineMode.Intersect);
            r = new Rectangle(r.X, r.Y, Width, Height);
            g.FillRectangle(new SolidBrush(BackColor), r);
            g.DrawString(Text, Font, new SolidBrush(ForeColor.IsEmpty ? Color.Black : ForeColor), r.X, r.Y);
            System.Windows.Forms.ControlPaint.DrawButton(g, r, ButtonState.All);
            g.SetClip(rgn, CombineMode.Replace);
        }
    }

    public class SpreadTextBox : TextBox, IEmbeddedControlSupport
    {
        public virtual Moving CanMove { get; set; } = Moving.None;
        public virtual Sizing CanSize { get; set; } = Sizing.None;
        public virtual ChildActivationPolicy ActivationPolicy { get; set; } = ChildActivationPolicy.Click;

        public void ControlPaint(Graphics g, Rectangle r, FarPoint.Win.Spread.Appearance appearance, object value, bool isSelected, bool isLocked, float zoomFactor)
        {
            Region rgn = g.Clip;
            g.SetClip(r, CombineMode.Intersect);
            g.FillRectangle(new SolidBrush(BackColor), r);
            g.DrawString(Text, Font, new SolidBrush(ForeColor), r.X, r.Y);
            g.SetClip(rgn, CombineMode.Replace);
        }
    }

    public class SpreadRadioButton : RadioButton, IEmbeddedControlSupport
    {
        public virtual Moving CanMove { get; set; } = Moving.None;
        public virtual Sizing CanSize { get; set; } = Sizing.None;
        public virtual ChildActivationPolicy ActivationPolicy { get; set; } = ChildActivationPolicy.Click;

        public void ControlPaint(Graphics g, Rectangle r, FarPoint.Win.Spread.Appearance appearance, object value, bool isSelected, bool isLocked, float zoomFactor)
        {
            Region rgn = g.Clip;
            g.SetClip(r, CombineMode.Intersect);
            r = new Rectangle(r.X, r.Y, Math.Min(Width, 12), Math.Min(Height, 16));

            System.Windows.Forms.ControlPaint.DrawRadioButton(g, r, Checked ? ButtonState.Checked : ButtonState.Normal);
            g.DrawString(Text, Font, new SolidBrush(ForeColor.IsEmpty ? Color.Black : ForeColor), r.X + r.Width, r.Y);

            g.SetClip(rgn, CombineMode.Replace);
        }
    }

    public class SpreadCheckBox : CheckBox, IEmbeddedControlSupport
    {
        public virtual Moving CanMove { get; set; } = Moving.None;
        public virtual Sizing CanSize { get; set; } = Sizing.None;
        public virtual ChildActivationPolicy ActivationPolicy { get; set; } = ChildActivationPolicy.Click;

        public SpreadCheckBox()
        {
            CheckedChanged += SpreadCheckBox_CheckedChanged;
        }

        private void SpreadCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            Text = Checked ? "True" : "False";
        }

        public void ControlPaint(Graphics g, Rectangle r, FarPoint.Win.Spread.Appearance appearance, object value, bool isSelected, bool isLocked, float zoomFactor)
        {
            Region rgn = g.Clip;
            g.SetClip(r, CombineMode.Intersect);
            r = new Rectangle(r.X, r.Y, Width, Height);

            System.Windows.Forms.ControlPaint.DrawCheckBox(g, r, isSelected ? ButtonState.Checked : ButtonState.Normal);
            g.SetClip(rgn, CombineMode.Replace);
        }
    }

    public class SpreadComboBox : ComboBox, IEmbeddedControlSupport
    {
        public virtual Moving CanMove { get; set; } = Moving.None;
        public virtual Sizing CanSize { get; set; } = Sizing.None;
        public virtual ChildActivationPolicy ActivationPolicy { get; set; } = ChildActivationPolicy.Click;

        public SpreadComboBox()
        {
            SelectedIndexChanged += SpreadComboBox_SelectedIndexChanged;

            Items.AddRange(new string[] { "One", "Two", "Three" });
        }

        private void SpreadComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            Text = SelectedItem.ToString();
        }

        public void ControlPaint(Graphics g, Rectangle r, FarPoint.Win.Spread.Appearance appearance, object value, bool isSelected, bool isLocked, float zoomFactor)
        {
            Region rgn = g.Clip;
            g.SetClip(r, CombineMode.Intersect);
            r = new Rectangle(r.X, r.Y, Width, Height);
            g.FillRectangle(new SolidBrush(BackColor), r);
            g.DrawString(Text, Font, new SolidBrush(ForeColor.IsEmpty ? Color.Black : ForeColor), r.X, r.Y);
            r.X = r.X + r.Width - SystemInformation.CaptionButtonSize.Width / 2;
            r.Width = SystemInformation.CaptionButtonSize.Width / 2;
            System.Windows.Forms.ControlPaint.DrawComboButton(g, r, ButtonState.Normal);

            g.SetClip(rgn, CombineMode.Replace);
        }
    }
}